<template>
  <div class="login-container">
    <!--<div class="container flex logo-wrapper">-->
    <!--<img src="union.png" class="logo"/>-->
    <!--<div class="logo__txt">福田文旅运营管理系统</div>-->
    <!--</div>-->
    <div class="login-container__inner">
      <!--<div class="login-container__bg"></div>-->
      <div class="container rel">
        <div class="merchant__title">
          <!--福田文旅运营管理系统-->
        </div>
      </div>
    </div>

    <el-form
      v-if="current === 'login'"
      ref="loginForm"
      size="small"
      :model="loginForm"
      :rules="loginRules"
      class="login-form"
      auto-complete="on"
      label-position="left"
    >

      <div class="title-container">
        <h3 class="title">账号登录</h3>
      </div>

      <el-form-item prop="username">
        <span class="svg-container">
          <svg-icon icon-class="user"/>
        </span>
        <el-input
          ref="username"
          v-model.trim="loginForm.username"
          placeholder="用户名"
          name="username"
          type="text"
          tabindex="1"
          auto-complete="off"
        />
      </el-form-item>

      <el-form-item prop="password">
        <span class="svg-container">
          <svg-icon icon-class="password"/>
        </span>
        <el-input
          :key="passwordType"
          ref="password"
          v-model.trim="loginForm.password"
          :type="passwordType"
          placeholder="密码"
          name="password"
          tabindex="2"
          auto-complete="off"
          @keyup.enter.native="handleLogin"
        />
        <span class="show-pwd" @click="showPwd">
          <svg-icon :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'"></svg-icon>
        </span>
      </el-form-item>

      <el-form-item prop="captcha" class="captcha-container">
        <span class="svg-container">
          <svg-icon icon-class="verification-code"></svg-icon>
        </span>
        <el-input
          ref="captcha"
          v-model.trim="loginForm.captcha"
          placeholder="图片验证码"
          auto-complete="off"
        ></el-input>
        <span class="captcha-img" @click="getCaptcha">
          <img :src="captcha" width="80" alt="图片丢失~">
        </span>
      </el-form-item>

      <el-button :loading="loading" type="danger" style="width:100%;margin-bottom:20px;" @click.native.prevent="handleLogin">登录</el-button>
      <div class="content-right">
        <!--<el-link> 忘记密码</el-link>-->
      </div>

    </el-form>

    <div class="reset-container" v-else-if='current === "resetpwd"'>
      <el-form
        ref="resetForm"
        size="small"
        :model="pwdForm"
        :rules="pwdFormRule"
        class="reset-form"
        auto-complete="on"
        label-position="left"
      >
        <div class="title-container">
          <h3 class="title">重置密码</h3>
        </div>
        <el-form-item label="当前密码" prop="oldPwd" required>
          <el-input
            v-model.trim="pwdForm.oldPwd"
            type="password"
            placeholder="请输入当前登录密码"
            tabindex="2"
            auto-complete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="设置密码" required prop="newPwd1">
          <el-input
            v-model.trim="pwdForm.newPwd1"
            type="password"
            placeholder="请输入密码"
          ></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="newPwd2">
          <el-input
            v-model.trim="pwdForm.newPwd2"
            type="password"
            placeholder="请重新输入密码"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="confirm-footer">
        <el-button size="mini" @click="cancelResetpwd">取 消</el-button>
        <el-button
          size="mini"
          type="primary"
          :loading="isChangPwding"
          @click="doChangePwd"
        >确 定
        </el-button
        >
      </div>
    </div>

    <vue2-verify
      @success="success"
      :mode="'pop'"
      :captchaType="'blockPuzzle'"
      :imgSize="{ width: '330px', height: '155px' }"
      ref="verify"
    >
    </vue2-verify>

    <div class="copyright">
      All Rights Reserved Powered by 福田文旅
      <!--<a class="text-color" href="https://beian.miit.gov.cn" target="_blank">ICP备案号：沪ICP备2023010123号</a>-->
    </div>

  </div>
</template>

<script>
import { validUsername, validPassword } from '@/utils/validate'
import Vue2Verify from '@/components/verifition/Verify'
import { managerApi } from '@/feature/system/infra/api/managerApi'
import { logoff, getCaptchaCode } from '@/infra/api/user'
import { arrayBufferToBase64 } from '@/utils/util'

export default {
  name: 'Login',
  components: { Vue2Verify },
  data() {
    const validateUsername = (rule, value, callback) => {
      if (!validUsername(value)) {
        callback(new Error('Please enter the correct user name'))
      } else {
        callback()
      }
    }
    const validatePassword = (rule, value, callback) => {
      if (!validPassword(value)) {
        callback(new Error('字母大小写数字特殊符号中至少3种，且大于8位'))
      } else {
        if (value === this.pwdForm.newPwd2 && value !== this.pwdForm.newPwd1) {
          callback(new Error('确认密码和设置密码不同！'))
        }
        callback()
      }
    }
    return {
      loginForm: {
        username: '',
        password: '',
        captcha: ''
      },
      loginRules: {
        username: [{ required: true, trigger: 'blur', message: '请输入用户名' }],
        password: [
          { required: true, trigger: 'blur', validator: validatePassword }
        ],
        captcha: [
          { required: true, trigger: 'blur', message: '请输入图片验证码'}
        ]
      },
      pwdForm: {
        newPwd2: '',
        newPwd1: '',
        oldPwd: ''
      },
      pwdFormRule: {
        oldPwd: [
          {
            required: true,
            message: "请输入当前用户的密码"
          }
        ],
        newPwd1: [
          {
            required: true,
            validator: validatePassword
          }
        ],
        newPwd2: [
          {
            required: true,
            validator: validatePassword
          }
        ]
      },
      isChangPwding: false,
      loading: false,
      passwordType: 'password',
      captcha: '',
      redirect: undefined,
      allowLogin: true,
      pwdTimes: 0,
      lockTime: 30,
      timer: undefined,
      current: ''
    }
  },
  watch: {
    $route: {
      handler: function(route) {
        this.redirect = route.query && route.query.redirect
      },
      immediate: true
    }
  },
  created() {
    this.current  = this.$route.query?.current ?? 'login'
  },
  mounted() {
    if (localStorage.getItem('pwdTimes')) {
      this.pwdTimes = localStorage.getItem('pwdTimes')
    } else {
      this.pwdTimes = 0
      localStorage.setItem('pwdTimes', 0)
    }
    if (localStorage.getItem('lockTime')) {
      this.lockTime = localStorage.getItem('lockTime')
    } else {
      this.lockTime = 30
      localStorage.setItem('lockTime', 30)
    }
    this.getCaptcha()
  },
  methods: {
    useVerify() {
      this.$refs.verify.show()
    },
    success(params) {
      // console.log(params)
      // return
      // params 返回的二次验证参数, 和登录参数一起回传给登录接口，方便后台进行二次验证
      this.loading = true
      this.loginForm.captchaVerification = params.captchaVerification
      // console.log(this.loginForm)
      this.$store.dispatch('user/login', this.loginForm).then(() => {
        this.pwdTimes = 0
        localStorage.setItem('pwdTimes', this.pwdTimes)
        this.lockTime = 30
        localStorage.setItem('lockTime', this.lockTime)
        this.$router.push({ path: this.redirect || '/' })
        location.reload()
        this.loading = false
      }).catch(() => {
        this.getCaptcha()
        localStorage.setItem('pwdTimes', ++this.pwdTimes)
        // 第三次密码失败，触发锁定，并且计时
        if (this.pwdTimes === 3) {
          this.allowLogin = false
          this.timer = setInterval(() => {
            if (this.lockTime > 0) {
              localStorage.setItem('lockTime', --this.lockTime)
            } else {
              clearInterval(this.timer)
              this.timer = undefined
              this.lockTime = 30
              localStorage.setItem('lockTime', this.lockTime)
              // 重新计数
              this.pwdTimes = 0
              localStorage.setItem('pwdTimes', this.pwdTimes)
              this.allowLogin = true
            }
          }, 60 * 1000)
        }
        this.loading = false
      })
    },
    showPwd() {
      if (this.passwordType === 'password') {
        this.passwordType = ''
      } else {
        this.passwordType = 'password'
      }
      this.$nextTick(() => {
        this.$refs.password.focus()
      })
    },
    handleLogin() {
      this.$refs.loginForm.validate(valid => {
        if (valid && this.allowLogin) {
          this.$refs.verify.show()
        } else {
          if(this.pwdTimes === 3) {
            this.$message.error('尝试过多，账号已锁定！')
          }
          return false
        }
      })
    },
    getCaptcha() {
      getCaptchaCode().then(response => {
        this.captcha = URL.createObjectURL(response.data)
      })
    },
    cancelResetpwd() {
      console.log("cancel");
      this.$store.dispatch('user/logout')
      this.$router.push('/login')
      location.reload();
    },
    doChangePwd() {
      this.$refs['resetForm'].validate((valid) => {
        if (valid) {
          console.log('pwd')
          this.isChangPwding = true
          managerApi.changeLoginPwd(this.pwdForm)
            .then((data) => {
              this.isChangPwding = false
              this.pwdForm = {}
              this.$refs['resetForm'].clearValidate()
              logoff()
              this.$store.dispatch('user/logout')
              this.$alert('修改密码成功,需要重新登录', '提示', {
                callback: action => {
                  this.$router.push('/login')
                  location.reload()
                }
              })
            })
            .catch((_) => {
              this.isChangPwding = false
            })
        }
      })
    },
  }
}
</script>

<style lang="scss">
/* 修复input 背景不协调 和光标变色 */
/* Detail see https://github.com/PanJiaChen/vue-element-admin/pull/927 */

$bg: #283443;
$light_gray: #fff;
$cursor: #fff;
//
//@supports (-webkit-mask: none) and (not (cater-color: $cursor)) {
//  .login-container .el-input input {
//    color: $cursor;
//  }
//}

/* reset element-ui css */
.login-container {
  .el-input {
    display: inline-block;
    height: 40px;
    width: 85%;

    input {
      background: #fff !important;
      border: none;
      //-webkit-appearance: none;
      //border-radius: 0px;
      //padding: 12px 5px 12px 15px;
      //color: $light_gray;
      //height: 47px;
      //caret-color: $cursor;

      //&:-webkit-autofill {
      //  box-shadow: 0 0 0px 1000px $bg inset !important;
      //  -webkit-text-fill-color: $cursor !important;
      //}
    }
  }

  .el-form-item {
    //border: 1px solid rgba(255, 255, 255, 0.1);
    border: 1px solid #eee;
    background: #fff;
    //background: rgba(0, 0, 0, 0.1);
    border-radius: 5px;
    color: #454545;
    margin-bottom: 20px;
  }
}
</style>

<style lang="scss" scoped>

$bg: #2d3a4b;
$dark_gray: #889aa4;
$light_gray: #eee;

.container {
  width: 1140px;
  margin: 0 auto;
}

.logo {
  width: 50px;
  height: 50px;
  margin: 20px 0;

  &__txt {
    color: #E33737;
    font-weight: bold;
    padding-left: 10px;
    font-size: 30px;
  }
}

.login-container {
  min-height: 100%;
  width: 100%;
  background-color: #ffff;
  //overflow: hidden;
  background-image: url("/2.jpg");
  background-size: cover;

  &__bg {
    background-image: url("/2.jpg");
    position: absolute;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    background-repeat: no-repeat;
    background-size: cover;
  }

  &__inner {
    //background-image: linear-gradient(180deg, #103bbc 0%, #00238c 100%);
    //width: 1440px;
    //height: 600px;
    position: relative;
    height: 100%;

    .container {
      //height: 600px;
    }
  }

  .login-form, .reset-container {
    //background: rgba(255,255,255,0.4);
    background: #fff;
    width: 320px;
    max-width: 100%;
    padding: 0 20px 0;
    height: 320px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    overflow: hidden;
    position: absolute;
    left: 66%;
    //top: 140px;
    top: 50%;
    transform: translateY(-50%);
    border-radius: 10px;
    color: #666;

    .captcha-container {
      .el-input {
        width: 55%;
      }
      .captcha-img {
        vertical-align: middle;
        img {
          vertical-align: middle;
        }
      }
    }
  }

  .reset-container {
    .el-input {
      width: 72%;
      height: 32px;
    }
  }

  .tips {
    font-size: 14px;
    color: #fff;
    margin-bottom: 10px;

    span {
      &:first-of-type {
        margin-right: 16px;
      }
    }
  }

  .svg-container {
    padding: 6px 5px 6px 15px;
    color: $dark_gray;
    vertical-align: middle;
    width: 30px;
    display: inline-block;
  }

  .title-container {
    position: relative;

    .title {
      font-size: 18px;
      color: #666;
      margin: 0px auto 10px auto;
      text-align: center;
      font-weight: bold;
    }
  }

  .show-pwd {
    position: absolute;
    right: 10px;
    top: 7px;
    font-size: 16px;
    color: $dark_gray;
    cursor: pointer;
    user-select: none;
  }
}

.merchant__title {
  color: #fff;
  font-size: 50px;
  font-weight: bold;
  letter-spacing: 10px;
  position: absolute;
  left: 30px;
  top: 250px;
  //background:-webkit-linear-gradient(red, red);
  background: #E33737;
  font-style: italic;
  -webkit-background-clip: text;
  -webkit-text-fill-color: #fff;
  -webkit-text-stroke: 6px transparent;
}

@media (max-width: 1140px) {
  .container {
    width: auto;
  }
  .merchant__title {
    top: 50px;
    left: 50%;
    transform: translateX(-50%);
    white-space: nowrap;
    font-size: 30px;
  }
  .login-container .login-form {
    left: 50%;
    //transform: translateX(-50%);
  }
  .logo-wrapper {
    display: none;
  }
}


.copyright {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  text-align: center;
  padding-bottom: 40px;
  font-family: MicrosoftYaHei;
  font-size: 14px;
  font-weight: normal;
  font-stretch: normal;
  letter-spacing: 0px;
  color: #ffffff;
  // 文字描边效果，描边颜色为蓝色，描边宽度为3px

  /* Standard syntax */
  text-stroke: 6px transparent;
  /* Vendor prefixes */
  -moz-text-stroke: 6px transparent;
  -ms-text-stroke: 6px transparent;
  -o-text-stroke: 6px transparent;
  -webkit-background-clip: text;
  -webkit-text-fill-color: #ffffff;
  -webkit-text-stroke: 6px transparent;
  background-color: #2b53a9;

  .text-color {
    margin-left: 20px;
    color: #ffffff;
    text-decoration: none;
  }
}

.confirm-footer {
  display: flex;
  justify-content: center;
}

// .el-form-item {
//   &.el-form-item--small {
//     width: 100%;
//   }
// }
// ::v-deep(.el-input--small) {
//   &.el-input__inner {
//     height: 100%;
//   }
// }

</style>
